# coding=UTF-8
'''
Created on 2018年4月26日

@author: lijie
'''
import pymysql
from utilites.common import Common

dbs=Common().get_database_config()
class MysqlHelper():
    
    def __init__(self,ev='test1',dbt='QA'):
        global dbs
        self.connect = pymysql.Connect(
            host=''+dbs[dbt][ev]['serverIP']+'',
            port=dbs[dbt][ev]['port'],
            user=''+dbs[dbt][ev]['username']+'',
            passwd=''+dbs[dbt][ev]['password']+'',
            db=''+dbs[dbt][ev]['dbname']+'',
            charset=''+dbs[dbt][ev]['charset']+'',
            cursorclass = pymysql.cursors.DictCursor
        )
        self.cursor = self.connect.cursor()
    
    def sqlquery(self,sql):
        '''执行查询
        arg:str sql,查询sql语句
        return: 返回查询到的所有结果list
        author: lijie
        '''
        try:
            self.cursor.execute(sql)
            return self.cursor.fetchall()
        except Exception as e:
            print(e)
        finally:
            self.connect.close()
          
    def exc(self,sql):
        '''执行新增，修改，删除操作
        arg:str sql,查询sql语句
        author: lijie
        '''
        try:
            self.cursor.execute(sql)   
            self.connect.commit()
        except Exception as e:
            print(e)
            self.connect.rollback()  
        finally:
            self.connect.close()
                
    def close_conn(self):
        self.connect.close()
        
    def excute(self,sql):
        '''执行不关闭链接
        '''
        try:
            self.cursor.execute(sql)   
            self.connect.commit()
        except Exception as e:
            print(e)
            self.connect.rollback()
            
    def query(self,sql):
        '''执行查询，不关闭链接
        arg:str sql,查询sql语句
        return: 返回查询到的所有结果list
        author: lijie
        '''
        try:
            self.cursor.execute(sql)
            return self.cursor.fetchall()
        except Exception as e:
            print(e)  
